package com.example.demo.data.model;

import android.util.Log;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class NewsList {

    public static List<News> newsList = new ArrayList<>();

    public static NewsAdapter adapter;

    public static String url = "https://api.jisuapi.com/news/get?channel=头条&start=@start@&num=10&appkey=d65c8d176fe7c273";


    public static void init(NewsAdapter adapter){
        NewsList.adapter = adapter;
        newsList.clear();
        loadNewsPage( 0);

    }

    private static void loadNewsPage(int offset) {
        new Thread(() -> {
            try{
                OkHttpClient client = new OkHttpClient();

                Request request = new Request.Builder() .url(url.replace("@start@", offset+"")) .build();
                Response response = client.newCall(request).execute();
                String body = response.body().string();
                JSONObject mapObj = JSONObject.parseObject(body);
                JSONArray array =  mapObj.getJSONObject("result").getJSONArray("list");
                for(int i=0;i< array.size();i++){
                    JSONObject item = array.getJSONObject(i);
                    News news = new News();
                    news.setTitle(item.getString("title"));
                    news.setCreateTime(item.getString("time"));
                    news.setSource(item.getString("src"));
                    news.setContent(item.getString("content"));
                    newsList.add(news);
                }
                adapter.notifyDataSetChanged();
            }catch (Exception e){
                Log.i("", Objects.requireNonNull(e.getMessage()));
            }
        }).start();

    }

    public static void addPage(NewsAdapter adapter){
        NewsList.adapter = adapter;
        loadNewsPage( newsList.size()+1);
    }
}
